package com.yoyo.schedule.zookeeper;

import com.yoyo.schedule.task_manager.TaskHandler;
import lombok.Getter;
import lombok.Setter;

import java.sql.Timestamp;
import java.util.Comparator;

class TaskHandlerComparator implements Comparator<TaskHandler> {
    @Setter
    @Getter
    String[] orderFields;

    public TaskHandlerComparator(String s) {
        if (s != null) {
            orderFields = s.toUpperCase().split(",");
        } else {
            orderFields = "task_type,own_sign,register_time,heartbeat_time,ip".toUpperCase().split(",");
        }
    }

    public int compareObject(String o1, String o2) {
        if (o1 == null && o2 == null) {
            return 0;
        } else if (o1 != null) {
            return o1.compareTo(o2);
        } else {
            return -1;
        }
    }

    public int compareObject(Timestamp o1, Timestamp o2) {
        if (o1 == null && o2 == null) {
            return 0;
        } else if (o1 != null) {
            return o1.compareTo(o2);
        } else {
            return -1;
        }
    }

    public int compare(TaskHandler o1, TaskHandler o2) {
        int result = 0;
        for (String name : orderFields) {
            if (name.equals("task_type")) {
                result = compareObject(o1.getTaskType(), o2.getTaskType());
                if (result != 0) {
                    return result;
                }
            } else if (name.equals("own_sign")) {
                result = compareObject(o1.getOwnSign(), o2.getOwnSign());
                if (result != 0) {
                    return result;
                }
            } else if (name.equals("register_time")) {
                result = compareObject(o1.getRegisterTime(), o2.getRegisterTime());
                if (result != 0) {
                    return result;
                }
            } else if (name.equals("heartbeat_time")) {
                result = compareObject(o1.getHeartBeatTime(), o2.getHeartBeatTime());
                if (result != 0) {
                    return result;
                }
            } else if (name.equals("ip")) {
                result = compareObject(o1.getIp(), o2.getIp());
                if (result != 0) {
                    return result;
                }
            } else if (name.equals("manager_factory")) {
                result = compareObject(o1.getMachineId(), o2.getMachineId());
                if (result != 0) {
                    return result;
                }
            }
        }
        return result;
    }
}
